import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:bot_toast/bot_toast.dart';
import '../../../data/services/channel_service.dart';
import '../../../data/services/alarm_service.dart';
import '../../../data/services/api_service.dart';

class HomeController extends GetxController {
  // 服务实例 - GetX规范
  final ChannelService _channelService = Get.find<ChannelService>();
  final AlarmService _alarmService = Get.find<AlarmService>();
  final ApiService _apiService = Get.find<ApiService>();

  // 响应式变量
  final _isLoading = false.obs;
  final _onlineChannels = 0.obs;
  final _offlineChannels = 0.obs;
  final _unreadCount = 0.obs;

  // Banner数据 - 直接使用Map
  final _bannerList = <Map<String, dynamic>>[].obs;
  final _isBannerLoading = false.obs;

  // 广告弹窗数据
  final _advertisementData = Rxn<Map<String, dynamic>>();
  final _isAdvertisementLoading = false.obs;

  // Getters
  bool get isLoading => _isLoading.value;
  int get onlineChannels => _onlineChannels.value;
  int get offlineChannels => _offlineChannels.value;
  int get unreadCount => _unreadCount.value;
  List<Map<String, dynamic>> get bannerList => _bannerList;
  bool get isBannerLoading => _isBannerLoading.value;
  Map<String, dynamic>? get advertisementData => _advertisementData.value;
  bool get isAdvertisementLoading => _isAdvertisementLoading.value;

  @override
  void onReady() {
    super.onReady();
    // 页面准备好后加载数据
    _loadHomeData();
    // 加载广告弹窗信息
    _loadAdvertisementInfos();
  }

  /// 加载首页数据
  Future<void> _loadHomeData() async {
    await Future.wait([
      _loadChannelStatistics(),
      _loadUnreadCount(),
      _loadBannerInfos(),
    ]);
  }

  /// 获取Banner信息
  Future<void> _loadBannerInfos() async {
    try {
      _isBannerLoading.value = true;
      print('🎯 开始获取Banner信息...');

      final response = await _apiService.getBannerInfos();
      final data = response['data'] as List<dynamic>?;

      if (data != null) {
        _bannerList.clear();
        for (final item in data) {
          if (item is Map<String, dynamic>) {
            _bannerList.add(item);
          }
        }
        print('✅ Banner信息获取成功，共${_bannerList.length}条');
      } else {
        print('❌ Banner数据为空');
      }
    } catch (e) {
      print('❌ 获取Banner信息失败: $e');
      // 保持原有的默认banner作为降级处理
    } finally {
      _isBannerLoading.value = false;
    }
  }

  /// 获取通道数统计
  Future<void> _loadChannelStatistics() async {
    try {
      final response = await _channelService.getChannelStatistics();
      final data = response['data'] as Map<String, dynamic>?;
      if (data != null) {
        _onlineChannels.value = data['onlineChannels'] as int? ?? 0;
        _offlineChannels.value = data['offlineChannels'] as int? ?? 0;
        print(
          '首页获取通道数统计成功：在线${_onlineChannels.value}，离线${_offlineChannels.value}',
        );
      }
    } catch (e) {
      print('首页获取通道数统计失败: $e');
    }
  }

  /// 获取未读消息数
  Future<void> _loadUnreadCount() async {
    try {
      final response = await _alarmService.getUnreadAlarmCount();
      final data = response['data'] as int?;
      if (data != null) {
        _unreadCount.value = data;
        print('首页获取未读消息数成功：$data');
      }
    } catch (e) {
      print('首页获取未读消息数失败: $e');
    }
  }

  /// 手动刷新数据
  Future<void> refreshData() async {
    _isLoading.value = true;
    await _loadHomeData();
    _isLoading.value = false;
  }

  /// 仅刷新未读消息数（更高效）
  Future<void> refreshUnreadCount() async {
    await _loadUnreadCount();
  }

  /// 获取广告弹窗信息
  Future<void> _loadAdvertisementInfos() async {
    try {
      _isAdvertisementLoading.value = true;
      print('🎯 开始获取广告弹窗信息...');

      final response = await _apiService.getAdvertisementInfos();
      final data = response['data'] as List<dynamic>?;

      if (data != null && data.isNotEmpty) {
        // 取第一个广告数据
        final advertisementItem = data.first as Map<String, dynamic>?;
        if (advertisementItem != null) {
          _advertisementData.value = advertisementItem;
          print('✅ 广告弹窗信息获取成功');

          // 延迟显示弹窗，确保页面已完全加载
          Future.delayed(const Duration(milliseconds: 500), () {
            _showAdvertisementDialog();
          });
        } else {
          print('❌ 广告弹窗数据格式错误');
        }
      } else {
        print('❌ 广告弹窗数据为空');
      }
    } catch (e) {
      print('❌ 获取广告弹窗信息失败: $e');
      // 不显示错误提示，静默失败
    } finally {
      _isAdvertisementLoading.value = false;
    }
  }

  /// 显示广告弹窗
  void _showAdvertisementDialog() {
    final data = _advertisementData.value;
    if (data == null) return;

    final imageUrl = data['imageUrl']?.toString() ?? '';
    final linkUrl = data['linkUrl']?.toString() ?? '';

    // 使用BotToast显示弹窗
    BotToast.showAnimationWidget(
      animationDuration: const Duration(milliseconds: 500),
      clickClose: true, // 允许点击关闭
      toastBuilder: (context) {
        return GestureDetector(
          onTap: () {
            BotToast.cleanAll(); // 点击空白处关闭
          },
          child: Container(
            width: double.infinity,
            height: double.infinity,
            color: Colors.black.withValues(alpha: 0.5),
            child: Center(
              child: GestureDetector(
                onTap: () {}, // 阻止事件冒泡
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    // 图片
                    Container(
                      width: 670.w,
                      height: 776.h,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(10.r),
                        image: DecorationImage(
                          image:
                              imageUrl.isNotEmpty
                                  ? NetworkImage(imageUrl)
                                  : const AssetImage(
                                        'assets/images/tanchuku_default.png',
                                      )
                                      as ImageProvider,
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),
                    SizedBox(height: 20.h),

                    // 了解更多按钮
                    if (linkUrl.isNotEmpty)
                      SizedBox(
                        width: 488.w,
                        height: 90.h,
                        child: ElevatedButton(
                          onPressed: () {
                            BotToast.cleanAll(); // 关闭弹窗
                            // 跳转到webview
                            Get.toNamed(
                              '/webview',
                              arguments: {'url': linkUrl, 'title': '了解更多'},
                            );
                          },
                          style: ElevatedButton.styleFrom(
                            backgroundColor: const Color(0xFF047FF7),
                            foregroundColor: Colors.white,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(10.r),
                            ),
                            elevation: 0,
                          ),
                          child: Text(
                            '了解更多',
                            style: TextStyle(
                              fontSize: 28.sp,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                      ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
      duration: const Duration(seconds: 10), // 10秒后自动关闭
      onlyOne: true, // 只显示一个
    );
  }

  /// Banner点击处理
  void onBannerTap(Map<String, dynamic> banner) {
    final linkUrl = banner['linkUrl']?.toString() ?? '';
    if (linkUrl.isNotEmpty) {
      // 如果有跳转链接，跳转到webview
      final title = banner['title']?.toString() ?? '';
      Get.toNamed(
        '/webview',
        arguments: {
          'url': linkUrl,
          'title': title.isNotEmpty ? title : 'Banner详情',
        },
      );
    } else {
      print('Banner无跳转链接');
    }
  }
}
